<?php
/**
 * Created by PhpStorm.
 * User: KaBuDa
 * Date: 2020/9/9
 * Time: 14:15
 */
namespace app\api\controller\v1;

use addons\epay\library\Service;
use app\api\validate\SupportValidate;
use app\api\validate\WhisStampsValidate;
use app\common\controller\Api;
use app\common\model\Bill;
use app\common\model\Earnings;
use app\common\model\Member;
use app\common\model\MemberMoney;
use app\common\model\WishCount;
use app\common\model\WishList;
use app\common\model\WishListMoney;
use app\common\model\WishOrder;
use fast\Random;
use think\Config;
use think\Db;
use think\Log;
use think\Request;
use Yansongda\Pay\Pay;


class Wish extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = '*';
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = '*';


    /**
     * 首页
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {

        $data=WishList::wishList();
        $member_id=$this->auth->id;
        $member_id=2;
        $model=new WishListMoney();
       $data= collection($data)->toArray();
        $queue=$this->queue($member_id);

       foreach ($data as &$list){
          $list['total']= $model->where(['wish_list_id'=>$list['id']])->sum('money');
      }
        $items=[
            'queue'=>$queue,
            'wish' => $data,
        ];
        $this->success('ok',$items);

    }

    /**
     * 心愿详情页
     * @param int $status
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function wishDetails($status=10)
    {
        $member_id=$this->auth->id;
        $member_id=1;

        switch ($status){
            case 20;
                $data=WishList::where(['member_id'=>$member_id,'status'=>10])->find();
                $data['total']=WishListMoney::where(['wish_list_id'=>$data['id']])->sum('money');
                $this->success('',['item'=>$data]);
            ;break;
            case 30;
//            if(!WishList::where(['member_id'=>$member_id,'status'=>30])->count(1)>0)
//                $this->error('Not fulfilling one\'s wish');
                $data=WishList::where(['member_id'=>$member_id,'status'=>$status])
                    ->whereOr(['status'=>20])
                    ->select()->each(function ($e){
                    return $e['total']=WishListMoney::where(['wish_list_id'=>$e['id']])->sum('money');
                });
                $this->success('',$data);
            ;break;
            default:
                $data=WishList::where('member_id',$member_id)
                    ->where("`status` = '10' OR  `status` = '0'")

                    ->find();
//                halt($data);

//                $sql="SELECT * FROM `fa_wish_list` WHERE  `member_id` = $member_id  AND `status` = '10' OR  `status` = '0' LIMIT 1";
//               $data= Db::name('wish_list')->query($sql);
//               halt();
//            halt($data->getLastSql());
                $data['queue']=$queue=$this->rank($member_id);

                $this->success('',['item'=>$data]);
        }
    }

    /** 流动信息
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function realTime()
    {
        $data=WishListMoney::with(['member'=>function($q){
           return $q->field('id,nickname');
       }])->order('id','desc')->select();
        foreach ($data as &$item){
           $item['createtime']=$this->timeTran($item['createtime']);
        }

        $this->success('',$data);
    }

    /**
     * @param $time
     * @return string
     */
    public  function timeTran($time)
    {
        $t = time() - $time;
        $f = array(
            '31536000' => '年',
            '2592000' => '个月',
            '604800' => '星期',
            '86400' => '天',
            '3600' => '小时',
            '60' => '分钟',
            '1' => '秒'
        );
        foreach ($f as $k => $v) {
            if (0 != $c = floor($t / (int)$k)) {
                return $c . $v . '前';
            }
        }
    }
    /**
     * 心愿详情
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function wishDetail()
    {
        $id=$this->request->request('id');
        if(empty($id)) $this->error('id不能为空');
        $model=new WishList();
        $data['list']=$model->where('id',$id)->with(['member'])->find();
        if(empty($data['list'])) $this->error('数据异常');
        $data['total']=WishListMoney::where(['wish_list_id'=>$id])->sum('money');
        $data['backer']=WishListMoney::with('member')
            ->field('SUM(money) total,id,member_id')
            ->where('wish_list_id',$id)
            ->group('member_id')
            ->select();
        $this->success('',$data);
    }


    /**
     * 心愿支持
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function support()
    {

        $member_id=$this->auth->id;
        $params=$this->request->post();
       $validate= validate(SupportValidate::class);
        if(!$validate->scene('support')->check($params)) $this->error($validate->getError());

//        $params['id']=3;
//        $params['money']=1;

            $member_id=11;

        Db::startTrans();
        if($params['money']>(MemberMoney::where(['member_id'=>$member_id])->value('money'))) $this->error('金额不足');
        if($member_id==WishList::where(['member_id'=>$member_id])->value('id')) $this->error('不能自己支持自己');
            $model=new MemberMoney();
            $result=$model->where(['member_id'=>$member_id])
                ->where('money','>',0)
                ->find();
            $money= Db::name('wish_list_money')->where('wish_list_id',$params['id'])->sum('money');
            if($params['money']>WishList::where('id',$params['id'])->value('money')) $this->error('支持金额不能超过心愿金额');

            if($params['money']-(WishList::where('id',$params['id'])->value('money')-$money)>0) $this->error('超出当前心愿可支持金额');
           $member= Member::where('member_id',$member_id)->find();



            $wishlistmoney= new WishListMoney();
            $wishlistmoney->member_id=$member_id;
            $wishlistmoney->wish_list_id=$params['id'];
            $wishlistmoney->money=$params['money'];
            $wishlistmoney->createtime=time();
            if($wishlistmoney->save()){
                MemberMoney::where(['member_id'=>$wishlistmoney->member_id])
                    ->update([
                        'money'=>MemberMoney::where(['member_id'=>$member_id])->max('money')-$params['money']
                    ]);
                $memeberMoney=Db::name('wish_list_money')->where('member_id',$member_id)->sum('money');
                if($memeberMoney>=1){

                    Member::where('member_id',$member_id)->update([
                        'status'=>10
                    ]);
                    $count=Db::name('wish_count')->where('member_id',$member_id)->find();

                      if($count['count']==1){
                          Member::where('member_id',$member['pid'])->setInc('number');

                          if(Member::where(['number'=>10,'member_id'=>$member['pid']])->update(['number'=>0])){
                              Member::where(['member_id'=>$member['pid']])->setInc('wish_stamps');
                          }
                      }
                }
                $member=Db::name('member')->find($member_id);
                Db::name('member')->where('member_id',$member_id)->update([
                    'donate'=>$member['donate']+$params['money']
                ]);
                if(WishListMoney::where(['wish_list_id'=>$params['id']])->sum('money')==WishList::where(['id'=>$params['id']])->value('money')){

                  $wish = WishList::get(['id'=>$params['id']])->save([
                        'status'=>30
                    ]);

                    if ($wish) {
                        $wishlist = WishList::where(['id' => $params['id'], 'status' => 30])->find();
                        $member = Member::get(['member_id'=>$wishlist['member_id']]);
                        $pid = Member::where(['pid' => $member['pid']])->value('pid');
                        $grandid = Member::where(['member_id' => $pid])->value('pid');

                        $data=MemberMoney::where('member_id',$wishlist['member_id'])->find();
                        if($data){
                            $res=MemberMoney::where('member_id',$wishlist['member_id'])->update([
                                'money' => $data['money']+$wishlist['money'] ,
                                'earnings' => $data['earnings'] + $wishlist['money'] ,
                                'createtime'=>time(),
                                'updatetime'=>time(),
                            ]);
                            Earnings::create([
                                'member_id'=>$wishlist['member_id'],
                                'earnings' =>$wishlist['money'] ,
                                'createtime'=>time()
                            ]);

                            Bill::create([
                              'member_id'=>$wishlist['member_id'],
                              'money'=>$wishlist['money'],
                              'type'=>10,
                              'createtime'=>time()
                            ]);
                        }


//                        if(!$res){
//                            $res=MemberMoney::where('member_id',$wishlist['member_id'])->update([
//                                'money' => $data['money'] +$wishlist['money'] * 0.03,
//                                'earnings' => $data['earnings'] + $wishlist['money'] * 0.03,
//                                'createtime'=>time(),
//                                'updatetime'=>time(),
//
//                            ]);
//                        }
                        if ($pid) {
                            $memberMoney = MemberMoney::where(['member_id' => $pid])->find();
                            if ($memberMoney) {
                                $res=MemberMoney::where(['member_id' => $pid])->update([
                                    'money' => $memberMoney['money'] +$wishlist['money'] * 0.03,
                                    'earnings' => $memberMoney['earnings'] + $wishlist['money'] * 0.03

                                ]);
                                Bill::create([
                                    'money'=>$wishlist['money'] * 0.03,
                                    'member_id'=>$pid,
                                    'type'=>20,
                                    'createtime'=>time()
                                ]);
                                if(!$res){
                                    MemberMoney::where(['member_id'=>$pid])->insert([
                                        'money' => $wishlist['money'] * 0.03,
                                        'earnings' => $memberMoney['earnings'] + $wishlist['money'] * 0.03,
                                        'createtime'=>time(),
                                        'updatetime'=>time()
                                    ]);
                                }
                            }
                        }
                        if ($grandid) {
                            $memberMoney = MemberMoney::where(['member_id' => $grandid])->find();
                            if ($memberMoney) {
                                MemberMoney::where(['member_id' => $grandid])->update([
                                    'money' =>  $memberMoney['money'] +$wishlist['money'] * 0.02,
                                    'earnings' => $memberMoney['earnings'] +$wishlist['money'] * 0.02
                                ]);

                                Bill::create([
                                    'money'=>$wishlist['money'] * 0.02,
                                    'member_id'=>$grandid,
                                    'type'=>30,
                                    'createtime'=>time()
                                ]);
                            }
                        }

                    }
                }
                Db::commit();
                $this->success('ok');
            }

            Db::rollback();
            $this->error('支持失败,请稍后再试');

    }

    /**
     * 发布愿望
     * @throws \think\Exception
     */
       public function issueWish()
       {
           $member_id = $this->auth->id;
           $member_id=2;
           $params = $this->request->post();
           $validate= \validate(WhisStampsValidate::class);
           if(!$validate->check($params)) $this->error($validate->getError());

           $money = WishListMoney::where(['member_id' => 2])->sum('money');
           if($params['money']>($money*2))  $this->error('申请金额最高为自己支持总额的2倍');
//           halt(WishList::where(['member_id'=>2,'status'=>0])->count());
           if(WishList::where(['member_id'=>$member_id,'status'=>0])->count()>=1) $this->error('心愿正在审核中,请耐心等待');

           $count = WishCount::where(['member_id' => $member_id])->value('count');
           if(!$count){
               WishCount::create([
                   'member_id'=>$member_id,
                   'createtime'=>time()
               ]);
           }
           $stamps= Member::where(['member_id'=>$member_id])->value('wish_stamps');
           if(!$stamps) $this->error('心愿券不足');
            if($money>=$this->money($count) && $stamps>0){
                Db::startTrans();
              WishCount::where(['member_id'=>$member_id])->setInc('count');
              Member::where(['member_id'=>$member_id])->setDec('wish_stamps');
               $create= WishList::create([
                    'title'   => $params['title'],
                    'content' => $params['content'],
                    'money'   => $params['money'],
                    'image'     =>$params['image'] ?? '',
                    'member_id'=>$member_id,
                    'createtime'=>time(),
                ]);

               if($create->id) Db::commit();
                Db::rollback();
              $this->success('发布成功');
            }
            $this->error('发布失败请查看是否满足申请条件');

       }

    /**
     * 图片上传
     */
    public function avatarUpload()
    {

        $file = $this->request->file('file');
        if (empty($file)) {
            $this->error(__('No file upload or server upload limit exceeded'));
        }

        //判断是否已经存在附件
        $sha1 = $file->hash();

        $upload = Config::get('upload');

        preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
        $type = strtolower($matches[2]);
        $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
        $size = (int)$upload['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
        $fileInfo = $file->getInfo();
        $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
        $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';

        $mimetypeArr = explode(',', strtolower($upload['mimetype']));
        $typeArr = explode('/', $fileInfo['type']);

        //禁止上传PHP和HTML文件
        if (in_array($fileInfo['type'], ['text/x-php', 'text/html']) || in_array($suffix, ['php', 'html', 'htm'])) {
            $this->error(__('Uploaded file format is limited'));
        }
        //验证文件后缀
        if ($upload['mimetype'] !== '*' &&
            (
                !in_array($suffix, $mimetypeArr)
                || (stripos($typeArr[0] . '/', $upload['mimetype']) !== false && (!in_array($fileInfo['type'], $mimetypeArr) && !in_array($typeArr[0] . '/*', $mimetypeArr)))
            )
        ) {
            $this->error(__('Uploaded file format is limited'));
        }
        //验证是否为图片文件
        $imagewidth = $imageheight = 0;
        if (in_array($fileInfo['type'], ['image/gif', 'image/jpg', 'image/jpeg', 'image/bmp', 'image/png', 'image/webp']) || in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'webp'])) {
            $imgInfo = getimagesize($fileInfo['tmp_name']);
            if (!$imgInfo || !isset($imgInfo[0]) || !isset($imgInfo[1])) {
                $this->error(__('Uploaded file is not a valid image'));
            }
            $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
            $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
        }
        $replaceArr = [
            '{year}'     => date("Y"),
            '{mon}'      => date("m"),
            '{day}'      => date("d"),
            '{hour}'     => date("H"),
            '{min}'      => date("i"),
            '{sec}'      => date("s"),
            '{random}'   => Random::alnum(16),
            '{random32}' => Random::alnum(32),
            '{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],
            '{suffix}'   => $suffix,
            '{.suffix}'  => $suffix ? '.' . $suffix : '',
            '{filemd5}'  => md5_file($fileInfo['tmp_name']),
        ];
        $savekey = $upload['savekey'];
        $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);

        $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
        $fileName = substr($savekey, strripos($savekey, '/') + 1);
        //
        $splInfo = $file->validate(['size' => $size])->move(ROOT_PATH . '/public' . $uploadDir, $fileName);
        if ($splInfo) {
            $params = array(
                'admin_id'    => 0,
                'user_id'     => (int)$this->auth->id,
                'filesize'    => $fileInfo['size'],
                'imagewidth'  => $imagewidth,
                'imageheight' => $imageheight,
                'imagetype'   => $suffix,
                'imageframes' => 0,
                'mimetype'    => $fileInfo['type'],
                'url'         => $uploadDir . $splInfo->getSaveName(),
                'uploadtime'  => time(),
                'storage'     => 'local',
                'sha1'        => $sha1,
            );
            $attachment = model("attachment");
            $attachment->data(array_filter($params));
            $attachment->save();
            \think\Hook::listen("upload_after", $attachment);
            $this->success(__('Upload successful'), [
                'url' => cdnurl($uploadDir . $splInfo->getSaveName(),true)
            ]);
        } else {
            // 上传失败获取错误信息
            $this->error($file->getError());
        }
    }


    /**
     * 返回金额
     * @param int $count
     * @return float|int
     */
       protected function money($count=0)
       {
           if($count == 0) {
               $money = 10;
           }elseif($count == 1) {
               $money = 100;
           } else {
               $money = pow(2, ($count - 1)) * 100;
           }
           return ($money);
       }



    /**
     * 排名
     * @throws \think\Exception
     */
   public function queue($member_id=null)
    {

        $query = new WishList();

        $wish=$query->where(['member_id' => $member_id])
            ->where("`status` = '10' OR  `status` = '0'")
            ->find();
        if($wish['status']==0){
            return ['queue'=>$wish];
        }
        $id = $query->where(['member_id' => $member_id])
            ->where("`status` = '10' ")
            ->value('id');

        $queue = WishList::where('id', '<=', $id)->where('status', 10)->count(1);
        $wishlist = $query->where(['member_id' => $member_id, 'status' => 10])->find();
        $money = WishList::where(['member_id' => $member_id, 'status' => 10])->value('money');
        if ($queue <= 10) {
            $queid = $query->where(['member_id' => $member_id, 'status' => 10])->find();

            $total = WishListMoney::where(['wish_list_id' => $queid['id']])->sum('money');

            $list = ['queue' => $queid, 'total' => $total];
            return $list;
        }
        $list = ['queue' => $queue, 'money' => $money,'wishlist'=>$wishlist];
        return $list;

//        $sql = "select count(1) as num from fa_wish_list where id <= (select id from fa_wish_list where member_id = {$member_id} and `status` = '10') and `status` = '10'";
//        return $query->query($sql);
    }

    public function rank($member_id)
    {
        $query = new WishList();
        $id = $query->where(['member_id' => $member_id, 'status' => 10])->value('id');
        $queue = WishList::where('id', '<=', $id)->where('status', 10)->count(1);
       return $queue;
    }


    /**
     *充值金额
     */
    public function rechargeAmount()
    {

        $member_id=$this->auth->id;
        $data=$this->request->post();
       $validate= \validate(SupportValidate::class);
       if(!$validate->scene('rechargeAmount')->check($data)) $this->error($validate->getError());
        if (!$data['type'] || !in_array($data['type'], ['alipay', 'wechat'])) $this->error("支付类型错误");

       $order=$this->createOrder($member_id,$data['money']);
       if(!$order->id) $this->error("服务器异常");

        $params = [
            'amount'=> $order['money'],
            'orderid'=> $order['sn_order'],
            'type'=> $data['type'],
            'title'=> "钱包充值",
            'notifyurl'=> $this->request->root(true) . '/addons/epay/index/notifyorder/paytype/alipay',
            'returnurl' => $this->request->root(true) . '/addons/epay/index/notifyorder/paytype/alipay', //
            'method'=>"app",
        ];

//        return Service::submitOrder($params);
       $this->success('',Service::submitOrder($params));
    }

    /**
     * 创建订单
     * @param $member_id
     * @param $money
     * @return mixed
     */
    protected function createOrder($member_id,$money)
    {
       return WishOrder::create([
           'member_id'  => $member_id,
           'money'      => $money,
           'sn_order'   => $this->snOrder(),
           'createtime' => time()
        ]);

    }

    /**
     * 生成订单编号
     * @return string
     */
    protected function snOrder()
    {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
       return $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
    }

    /**
     * 支付宝提现
     * @return \think\response\Json
     */
    public function tt($phone,$money)
    {



        import("aop.AopCertClient");
        import("aop.request.AlipayFundTransToaccountTransferRequest");
         $aopclient= new \AopCertClient();
        $appCertPath = 'http://www.wish.com' .'/test/appCertPublicKey_2021001193655488.crt';
        $alipayCertPath = 'http://www.wish.com' .'/test/alipayCertPublicKey_RSA2.crt';
        $rootCertPath = 'http://www.wish.com' .'/test/alipayRootCert.crt';

         $aopclient->appId=Config::get('alipay.app_id');
         $aopclient->alipayrsaPublicKey = $aopclient->getPublicKey($alipayCertPath);//调用getPublicKey从支付宝公钥证书中提取公钥
         $aopclient->rsaPrivateKey='MIIEpQIBAAKCAQEAoH/wFMXC9vsjvyrCCY/KChkIo+j+/7kbGlZsIop5KYtbQmbc9TPkPugo1ZR5giOoyyVqHhG4qA9RdjGbllvym5Q/08FzNfjFDCYwgrlAAp7qY4lE92kry4AP7s2L8uE9h4jrZtWxFAXhZo3aurGrxAFeiyX1i2C5RWRY5noEcLwjCDpMBiyQWMLLixQSU12fJcQ+wGVtJzGsWKCP2Mg8FBLLV4ds+A+XtQtffKoewmQ+txuOFGihNc+MLYBkK4D75OHqdfinYn4LsSrQ0m5seA41OSwV3pU9xEO2+iOvIEj5VVoeOihHH40y33dTcTfGH34AT0k3t2Ylf19IGyGwsQIDAQABAoIBADvUNTypE6pZp9OlLru9vATTnCLtwdC1weKpgJnHoK7Z4eT4zzkgZN8GT+J9/GWEwXEou0wGMx2CyE0U5PjBwcg5FSnsnPPrjhifS8oPIEtZzenYy7qmm8q6LDZKrPaW/AbABXBKDD54irNeAcFCZdMk54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SA2';
         $aopclient->format='json';
//         $aopclient->alipayCertSN=$this->request->root(true) .'/test/alipayCertPublicKey_RSA2.crt';
         $aopclient->alipayRootCertSN=$aopclient->getRootCertSN($rootCertPath);
         $aopclient->appCertSN=$aopclient->getCertSN($appCertPath);

         $aopclient->isCheckAlipayPublicCert= true;
         $request=new \AlipayFundTransToaccountTransferRequest();
//         $request->setBizContent(json_encode([
//             'out_biz_no'=>time(),
//             'payee_type'    => 'ALIPAY_LOGONID',
//             'payee_account' => 18111349993,
//             'trans_amount'        => 0.1,
//             'product_code'=>'TRANS_ACCOUNT_NO_PWD',
//             'payee_info'=>[
//                 'identity'=>'17708119603',
//                 'identity_type'=>'ALIPAY_LOGON_ID',
//                 'name'=>'梁静'
//             ],
//             'biz_scene'=>'DIRECT_TRANSFER'
//         ]));
//       halt(number_format($money * 0.8,2));
     $data=json_encode([
       'out_biz_no'=>time().mt_rand(0000,9999),
         'payee_type' =>'ALIPAY_LOGONID',
         'payee_account'=>$phone,
         'amount'=>  number_format($money*0.8,2),
         'remark'=>'提现到账'
     ]);
        $request->setBizContent($data
        );
     $res=$aopclient->execute($request);
     $res=$this->object_to_array($res);

        if($res["alipay_fund_trans_toaccount_transfer_response"]['code']==10000 && $res["alipay_fund_trans_toaccount_transfer_response"]['msg']=='Success'){

            return 1;
        }else{
            return $res["alipay_fund_trans_toaccount_transfer_response"]['sub_msg'];
        }


    }

    public function object_to_array($obj){
        $_arr=is_object($obj)?get_object_vars($obj):$obj;
        $arr = null;
        foreach($_arr as $key=>$val){
            $val=(is_array($val))||is_object($val)?$this->object_to_array($val):$val;
            $arr[$key]=$val;
        }
        return $arr;
    }
    /**
     * 微信提现
     * @return \think\response\Json
     */
    public function ww()
    {

        $order = [
            'partner_trade_no' => '31321dsfs',              //商户订单号
            'openid' => 'sdfsdsf',                        //收款人的openid
            'check_name' => 'NO_CHECK',            //NO_CHECK：不校验真实姓名\FORCE_CHECK：强校验真实姓名
            // 're_user_name'=>'张三',              //check_name为 FORCE_CHECK 校验实名的时候必须提交
            'amount' => '1',                       //企业付款金额，单位为分
            'type'=>'app',
            'desc' => '帐户提现',                  //付款说明
        ];

        $config = Service::getConfig('wechat');
        $pay=new Pay($config);
        $result = $pay->driver('wechat')->gateway('transfer')->pay($order);
        return json($result);
    }

    public function alip()
    {
        $data=$this->request->request();
        $member_id=$this->auth->id;
        $order=$this->createOrder($member_id,$data['money']);
        if(!$order->id) $this->error("服务器异常");
        import('aop.AopClient');
        import('aop.request.AlipayTradeAppPayRequest');
        $aop=new \AopClient();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = 2021001197635559;
        $aop->rsaPrivateKey = 'MIIEowIBAAKCAQEAgh8x5UmXSR0Mu2Ny0iSUR6n21gK6ksIpNNn2qmC3bWc2diqqUeshxRRv1Nox+TzFyqY/wY8qp2+A+kbIi0Bg/E8SyRbAvJbcSfWTCbGkYjcjcDQb1P/dMDcnjCIx1XuB4oTN5cU8sV2VAGJ3DwHTj198ewvIuQgsv09+SopiMLt9WAE+5M/wCUEg0wUqzZwiVfu4FUwAmSgnqzIIFVaSpHp5klhXOK9Hp22C6rQbOGfgBLzLm5IZhGuIEIAkMYnR5hoZ73t/8jjEZB9Fs0nTF684yUFXI6x2YaGgD92RTTIBnUE7o0UrSwJUgx9J5S880J79gmql3kw/QmF2SONcKwIDAQABAoIBADHijblulh5Ekc4BWVKxDVvQED6Ju0dqQmvtqAA3pfq+WAXDY5qWP1MT+6+pmwEHSHjhdY3aOisIt3S70ER6gPQZyITpQSjL2VZNXHqZ7QBuTRrGD2mAUica7gFuVpaWi/vwmBMfo54H14jXNve85oOPwuRVZzVwqd8KNcuT9ALkQB/qY1jxLDSpIDjnJz2zO+KZnBK2r5wZLRAcYPFqtuEnLlE+yl1yrV3PaCIxpriFnPZytmZzimhDkseg3uMSuD8hpr7NJyyy+jtI3j8RDh6eA+5sqE4XqXtpTQ273o6Z8xDv8S//TbiXOEgAoZLNn7s43Ntdh7X/uuO1g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8sV2VAGJ3DwHTj198ewvIuQgsv09+SopiMLt9WAE+5M/wCUEg0wUqzZwiVfu4FUwAmSgnqzIIFVaSpHp5klhXOK9Hp22C6rQbOGfgBLzLm5IZhGuIEIAkMYnR5hoZ73t/8jjEZB9Fs0nTF684yUFXI6x2YaGgD92RTTIBnUE7o0UrSwJUgx9J5S880J79gmql3kw/QmF2SONcKwIDAQAB';
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'utf-8';
        $aop->format = 'json';
        $request=new \AlipayTradeAppPayRequest();
        $data=json_encode([
            'body'            =>'充值',
            'subject'         =>'星月网络科技有限公司',
            'out_trade_no'    =>$order['sn_order'],
            'total_amount'    =>$order['money']
        ]);
        $request->setBizContent($data);
        $response = $aop->sdkExecute($request);
        $this->success('',$response);
    }

    public function notifyrul()
    {
        $update=Db::name('wish_order')->where('sn_order','J925984519199804')->setField([
            'status'=>10,
            'updatetime'=>time(),
            'money'=>1
        ]);
        dump($this->request->root(true));
    }
}